import '../sass/common.scss';
import { initHeaderFooter } from './gopLib/initHeaderFooter';
import * as tools from './tools';
jQuery.support.cors = true;
const VideoList = {};
$(function () {
  initHeaderFooter('vedio');
  init();

  //目录切换
  $(document).on('click', '.vedio-kinds-wrap .item', function () {
    if (!$(this).hasClass('active')) {
      let id = $(this).attr('data-id');
      $(this).siblings().removeClass('active');
      $(this).addClass('active');
      getVideo(id);
    }
  })

  //视频跳转
  $(document).on('click', '.vedio-cover', function () {
    if ($(this).hasClass('disabled')) {
      alert('抱歉，您没有权限观看该视频！');
      return
    }
    location.href = './videoPlay.html?id=' + $(this).attr('data-id')
  })
})

function init() {
  getContent();
}

function getContent() {
  let data = [];
  $.ajax({
    url: tools.apiUrl + 'videoDirectory/listAll',
    type: 'get',
    data : {
      status : 0
    },
    success: function (res) {
      data = res.data;
      if(data.length <= 0) {
        $('.vedio-kinds').hide();
      }else {
        renderContent(data);
      }
    }
  })
}

function renderContent(data) {
  let content = '';
  data.map((val, index) => {
    if (index == 0) {
      getVideo(val.id);
    }
    if (val.status == 0) {
      content += `
      <div class="item ${index == 0 ? 'active' : ''}" data-id="${val.id}">
          <span>${val.name}</span>
      </div>
      `
    }
  })
  $('.vedio-kinds-wrap').html(content);
}

function getVideo(derictoryId) {
  if (VideoList[derictoryId]) {
    renderVideo(VideoList[derictoryId]);
  } else {
    $.ajax({
      url: tools.apiUrl + 'videoTutorial/getListByDerictoryId',
      type: 'get',
      data: {
        derictoryId
      },
      success: function (res) {
        VideoList[derictoryId] = res.data;
        renderVideo(res.data);
      }
    })
  }
}
//渲染处理视频
function renderVideo(videos) {
  const loginInfo = sessionStorage.getItem('loginInfo');
  let loginObj = null;
  let type = -1;
  if (loginInfo) {
    loginObj = JSON.parse(loginInfo);
    type = loginObj.account.type;
  }
  let videosHtml = videos.map((val) => {
    let dotName = '';
    if(val.resourceUrl) {
      let arr = val.resourceUrl.split('.');
      dotName = arr[arr.length - 1];
    }
    return `
      <div class="vedio" >
          <div class="vedio-cover ${val.url ? '' : 'disabled'}" data-id="${val.id}" style="background: url(${val.image_url}) no-repeat;background-size: cover;background-position: 50% 50%;">
              <img src="../src/images/gop_1.1/${val.url ? 'on' : 'off'}.png" alt="">
          </div>
          <div class="vedio-panel">
              <p>${val.title}</p>
              ${val.url && val.resourceUrl? `<a href="${val.resourceUrl}?fileName=${val.title}" download="${val.title}.${dotName}">下载资料</a>` : '<a class="disabled">下载资料</a>'}
          </div>
      </div>
    `
  })
  $('.vedio-list-box').html(videosHtml.join(''))
}